import React, { useState, useEffect } from 'react';
import { Form, Input, Button, Picker, ImageUploader, TextArea, Collapse } from 'antd-mobile';
import { AddOutline, DownOutline, UpOutline, AddCircleOutline } from 'antd-mobile-icons';
import styles from './index.module.less';
import TagSelector from '@/components/TagSelector';
import HeaderNav from "@/components/header-nav";
import { useSearchParams } from 'react-router-dom'
import { showErrorToast, showSuccessToast } from '@/utils/customToast';
const { createWorldRole, getUserWorldBookDetails, editRole } = $globalServicer('world')
import { world_categoryColumns, era_backgroundColumns, genderColumns, raceColumns } from '@/utils/constant'
import { handleImageUpload } from '@/utils/upload'
import CreationMethod from '../components/creation-method';
import AiCreation from '../components/ai-creation';
import { defaultRoleCover, defaultNpcCover } from '@/utils/config';
const WorldCreationForm = () => {
  const [form] = Form.useForm();
  const [params] = useSearchParams();
  console.log("🚀 ~ ItemCrad ~ params:", params)
  const id = params.get('id');
  const type = params.get('type');
  const customNavigate = $globalNavigate()
  const [worldInfo, setWorldInfo] = useState(null)
  const [roleCount, setRoleCount] = useState(0);
  const [submitting, setSubmitting] = useState(false);
  const [showAiInput, setShowAiInput] = useState(false)
  const [activeKey, setActiveKey] = useState('')
  const [isRequired, setIsRequired] = useState(true)
  const [worldTypeVisible, setWorldTypeVisible] = useState(false);
  const [eraBackgroundVisible, setEraBackgroundVisible] = useState(false);
  const [genderVisible, setGenderVisible] = useState(false);
  const [raceVisible, setRaceVisible] = useState(false);
  useEffect(() => {
    if (id) {
      getUserWorldBookDetails(id).then(res => {
        debugger
        const npcs = res.npcs.map(item => {

          if (item.description.gender && !genderColumns.some(it => it.value == item.description.gender)) {
            genderColumns.push({ label: item.description.gender, value: item.description.gender })
          }

          if (item.description.race && !raceColumns.some(it => it.value == item.description.race)) {
            raceColumns.push({ label: item.description.race, value: item.description.race })
          }

          return {
            name: item.name,
            cover: [{
              url: item.cover,
              path: item.cover
            }],
            gender: [item.description.gender],
            age: item.description.age,
            race: [item.description.race],
            appearance: item.description.appearance,
            background: item.description.background,
            personality: item.description.personality,
          }
        })
        const result = {
          cover: [
            {
              url: res.cover,
              path: res.cover
            }
          ],
          name: res.name,
          world_category: [res.description.world_category],
          world_era: [res.description.world_era],
          world_map: res.description.world_map,
          world_faction: res.description.world_faction,
          world_rules: res.description.world_rules,
          custom_content: res.description.custom_content,
          first_message: res.first_message,
          npcs: npcs,
        }

        if (res.description.world_category && !world_categoryColumns.some(item => item.value === res.description.world_category)) {
          world_categoryColumns.push({ label: res.description.world_category, value: res.description.world_category })
        }

        if (res.description.world_era && !era_backgroundColumns.some(item => item.value === res.description.world_era)) {
          era_backgroundColumns.push({ label: res.description.world_era, value: res.description.world_era })
        }

        setWorldInfo(res)
        form.setFieldsValue(result)
      });
      setActiveKey('1')
    }
  }, [])
  const onFinish = (values) => {
    if (submitting) return
    try {
      if (values?.npcs === undefined || values?.npcs.length === 0) {
        showErrorToast('最少必须添加一个主要角色');
        return
      }
      const retultRoles = values?.npcs?.map(item => {
        return {
          name: item.name,
          cover: item.cover[0].url,
          description: {
            gender: item?.gender?.[0],
            age: item?.age,
            race: item?.race?.[0],
            appearance: item?.appearance,
            background: item?.background,
            personality: item?.personality,
          }
        }
      })
      let submitData = {
        cover: values.cover[0].url,
        name: values.name,
        description: {
          world_category: values?.world_category?.[0],
          world_era: values?.world_era?.[0],
          world_map: values?.world_map,
          world_faction: values?.world_faction,
          world_rules: values?.world_rules,
          custom_content: values?.custom_content,
        },
        first_message: values?.first_message,
        npcs: retultRoles,
        type: 2,
      }
      setSubmitting(true);
      if (id && type === 'edit') {
        submitData.id = id
        console.log(`------submitData----2`, submitData)
        editRole(submitData).then(res => {
          console.log(`------res`, res)
          showSuccessToast('编辑成功')
          customNavigate(`/world`)
        })
      } else {
        createWorldRole(submitData).then(res => {
          showSuccessToast('创建成功')
          customNavigate(`/world`)
          handleSetSessionItem('childReloads', true);
        })
      }
    } catch (error) {
      showErrorToast('提交失败，请重试');
    } finally {
      setSubmitting(false);
    }
  };
  const handleSetSessionItem = (key, value) => {
    sessionStorage.setItem(key, value);
    const parentWindow = window;
    parentWindow.sessionStorage.setItem(key, value);
  }
  const handleAddOption = (option) => {
  }

  // 创建方式选择回调
  const handleSelMethod = (type) => {
    console.log("🚀 ~ handleSelMethod ~ type:", type)
    setShowAiInput(type === 'ai');
  }

  // 处理AI输入结果
  const handleAiResult = (res) => {
    console.log("🚀 ~ handleAiResult ~ result:", res)
    const npcs = res.npcs.map(item => {

      if (item.description.gender && !genderColumns.some(it => it.value == item.description.gender)) {
        genderColumns.push({ label: item.description.gender, value: item.description.gender })
      }

      if (item.description.race && !raceColumns.some(it => it.value == item.description.race)) {
        raceColumns.push({ label: item.description.race, value: item.description.race })
      }

      return {
        name: item.name,
        cover: [],
        gender: item.description.gender ? [item.description.gender] : null,
        age: item.description.age,
        race: item.description.race ? [item.description.race] : null,
        appearance: item.description.appearance,
        background: item.description.background,
        personality: item.description.personality,
      }
    })
    const result = {
      cover: [],
      name: res.name,
      world_category: res.description.world_category ? [res.description.world_category] : null,
      world_era: res.description.world_era ? [res.description.world_era] : null,
      world_map: res.description.world_map,
      world_faction: res.description.world_faction,
      world_rules: res.description.world_rules,
      custom_content: res.description.custom_content,
      first_message: res.first_message,
      npcs: npcs,
    }

    if (res.description.world_category && !world_categoryColumns.some(item => item.value === res.description.world_category)) {
      world_categoryColumns.push({ label: res.description.world_category, value: res.description.world_category })
    }

    if (res.description.world_era && !era_backgroundColumns.some(item => item.value === res.description.world_era)) {
      era_backgroundColumns.push({ label: res.description.world_era, value: res.description.world_era })
    }

    setWorldInfo(res)
    form.setFieldsValue(result)
    setActiveKey('1')
  }

  return (
    <div className={styles.formContainer}>
      <div className="header">
        <HeaderNav backArrow={true} title={`${id && type === 'edit' ? '修改' : '创建'}世界卡`}></HeaderNav>
      </div>

      {/* 智能创建输入框 */}
      <AiCreation show={showAiInput} type={2} onResult={handleAiResult} />

      {/* 世界名称20字，世界分类20字，时代背景50字，
      故事开场白1300字
      世界地图200字，主要势力500字，世界特殊规则300字
      主要npc
      姓名10字，性别10字，年龄10字，种族20字，
      外貌衣着：300字，人物背景300字，性格特点300字
      自定义内容：300字 */}
      <Form
        form={form}
        onFinish={onFinish}
        footer={
          <div className={styles.footer}>
            <Button
              className={styles.submitButton}
              type='submit'
              loading={submitting}
              disabled={submitting}
            >{submitting ? '提交中...' : '完成'}</Button>
          </div>
        }
      >
        <Form.Item 
          name="cover" 
          initialValue={[{
          url: defaultRoleCover,
          path: defaultRoleCover
          }]} 
          label="世界图片" className={styles.imageItem} required={isRequired} rules={[{ required: isRequired, message: '世界图片不能为空' }]}>
          <ImageUploader
            style={{ '--cell-size': '66px' }}
            className={styles.uploadWrapper}
            upload={handleImageUpload}
            maxCount={1}
            onDelete={() => {
              return { beforeDelete: () => true };
            }} />
        </Form.Item>
        <Form.Item name="name" label="世界名称" help='字数上限20' required={isRequired} rules={[{ required: isRequired, message: '世界名称不能为空' }]}>
          <Input placeholder="输入世界名称，例1火影忍者，例2哈利波特世界。（字数上限20）" maxLength={20} />
        </Form.Item>
        {/* world_category: '世界分类',
        world_era: '时代背景',
        world_map: '世界地图',
        world_faction: '主要势力',
        world_rules: '世界特殊规则' 
        custom_content: '自定义内容'
        */}
        <TagSelector
          name="world_category"
          label="世界分类"
          options={world_categoryColumns}
          multiple={false}
          maxCount={20}
          help='字数上限20'
          onAddOption={handleAddOption}
          required={isRequired}
          rules={[{ required: isRequired, message: '世界分类不能为空' }]}
        />
        {/* <Form.Item name="world_category" label=" 世界分类" help=''>
          <Input placeholder="请选择世界分类" onClick={() => {
            setWorldTypeVisible(true)
          }} />
        </Form.Item> */}
        {/* 时代背景 */}
        <TagSelector
          name="world_era"
          label="世界时代背景"
          options={era_backgroundColumns}
          multiple={false}
          maxCount={50}
          help='字数上限50'
          onAddOption={handleAddOption}
          required={isRequired}
          rules={[{ required: isRequired, message: '世界时代背景不能为空' }]}
        />
        {/* <Form.Item name="world_era" label="时代背景" help=''>
          <Input placeholder="请选择时代背景" onClick={() => {
            setEraBackgroundVisible(true)
          }} />
        </Form.Item> */}
        {/* <Form.Item name="description" label="世界描述" help='字数上限3000'>
          <TextArea placeholder="输入世界描述，世界的世界背景设定，世界起源和势力，世界地图，世界规则等。例如：哈利波特世界中，魔法世界与麻瓜世界并存。(字数上限3000)" rows={3} maxLength={6000} />
        </Form.Item> */}
        <Form.Item name="first_message" label="故事开场白" help='字数上限1980' required={isRequired} rules={[{ required: isRequired, message: '故事开场白不能为空' }]}>
          <TextArea rows={4} placeholder="输入开启聊天后第一句对话，例如：通往霍格沃兹的火车马上就要启程了...字数上限1980）" maxLength={1980} />
        </Form.Item>

        <Collapse
          activeKey={activeKey}
          onChange={(activeKey) => {
            setActiveKey(activeKey)
          }}
        >
          <Collapse.Panel
            key='1'
            title={activeKey?.indexOf('1') ? '展开' : '收起'}
            className={styles.collapsePanelWrapper}
          >
            <Form.Item name="world_map" label="世界地图" help='字数上限200'>
              <TextArea rows={4} placeholder="请输入世界地图" maxLength={200} />
            </Form.Item>
            <Form.Item name="world_faction" label="主要势力" help='字数上限500'>
              <TextArea rows={4} placeholder="请输入主要势力" maxLength={500} />
            </Form.Item>
            <Form.Item name="world_rules" label="世界特殊规则" help='字数上限300'>
              <TextArea rows={4} placeholder="请输入世界特殊规则" maxLength={300} />
            </Form.Item>
            <Form.Item name={'custom_content'} label="自定义内容" help='字数上限300'>
              <TextArea rows={4} placeholder="请输入自定义内容" maxLength={300} />
            </Form.Item>
            <Form.Array
              name='npcs'
              initialValue={[{
                cover: [
                  {
                    url: defaultNpcCover,
                    path: defaultNpcCover
                  }
                ]
              }]}
              onAdd={operation => {
                const currentRoles = form.getFieldValue('npcs') || [];
                setRoleCount(prevCount => prevCount + 1);
                if (currentRoles.length < 3) {
                  operation.add({ name: '', cover: [{
                    url: defaultNpcCover,
                    path: defaultNpcCover
                  }]});
                } else {
                  showErrorToast('最多只能添加三个角色');
                }
              }}
              renderAdd={() => (
                roleCount < 3 ? (
                  <span>
                    <AddCircleOutline /> 添加主要角色
                  </span>
                ) : null
              )}
              renderHeader={({ index }, { remove }) => (
                <div className={styles.addRoleHeader}>
                  <span>添加该世界主要角色{index + 1}</span>
                  {
                    // initialValue.length > 1 && (
                    <a onClick={() => remove(index)} style={{ float: 'right' }}>
                      删除
                    </a>
                    // )
                  }
                </div>
              )}
            >
              {fields =>
                fields.map(({ index }) => (
                  <div key={index} className={styles.roleListWrapper}>
                    <div className={styles.roleListTopWrapper}>
                      <Form.Item
                        name={[index, 'cover']}
                        label='角色头像'
                        key={index}
                        required={isRequired}
                        rules={[{ required: true, message: '角色头像不能为空' }]}
                        className={styles.roleImageItem}
                      >
                        <ImageUploader
                          style={{ '--cell-size': '48px' }}
                          className={styles.uploadWrapper}
                          upload={handleImageUpload}
                          maxCount={1}
                          onDelete={() => {
                            return { beforeDelete: () => true };
                          }}
                        />
                      </Form.Item>
                      <Form.Item name={[index, 'name']} label='角色名称' className={styles.roleNameItem} help='字数上限10'>
                        <Input placeholder={`输入这个世界中存在的主要人物名称（字数上限10）`} maxLength={20} />
                      </Form.Item>
                    </div>
                    {/* 
                      gender: '性别',
                      age: '年龄',
                      race: '种族',
                      appearance: '外貌衣着',
                      background: '人物背景',
                      personality: '性格特点' 
                    */}
                    {/* <Form.Item name={[index, 'gender']} label='性别' help=''>
                    <Input placeholder="请选择性别" onClick={() => {
                      setGenderVisible(true)
                    }} />
                  </Form.Item> */}
                    <TagSelector
                      name={[index, 'gender']}
                      label="性别"
                      maxCount={10}
                      help='字数上限10'
                      options={genderColumns}
                      multiple={false}
                      onAddOption={handleAddOption}
                      required={isRequired}
                      rules={[{ required: isRequired, message: '角色性别不能为空' }]}
                    />
                    <Form.Item name={[index, 'age']} label='年龄' help='字数上限10'>
                      <Input placeholder="请输入年龄" maxLength={10} />
                    </Form.Item>
                    <TagSelector
                      name={[index, 'race']}
                      label="种族"
                      maxCount={20}
                      help='字数上限20'
                      options={raceColumns}
                      multiple={false}
                      onAddOption={handleAddOption}
                    />
                    <Form.Item name={[index, 'appearance']} label='外貌衣着' help='字数上限300'>
                      <TextArea rows={4} placeholder="请输入外貌衣着" maxLength={300} />
                    </Form.Item>
                    <Form.Item name={[index, 'background']} label='人物背景' help='字数上限300'>
                      <TextArea rows={4} placeholder="请输入人物背景" maxLength={300} />
                    </Form.Item>
                    <Form.Item name={[index, 'personality']} label='性格特点' help='字数上限300'>
                      <TextArea rows={4} placeholder="请输入性格特点" maxLength={300} />
                    </Form.Item>

                    {/* <Form.Item name={[index, 'description']} label='角色描述' help='字数上限3000'>
                    <TextArea placeholder="输入角色详细描述，姓名、性别、外貌、衣着、性格、能力、人物关系、对话示例等等。例如：赫敏是一名女性(字数上限3000)"
                      rows={3}
                      maxLength={6000}
                    />
                  </Form.Item> */}
                  </div>
                ))
              }
            </Form.Array>
          </Collapse.Panel>
        </Collapse>
        {/* <div className={styles.expandableSection}>
          <div className={styles.sectionHeader}>
            <span>世界主要角色添加</span>
            {
              expandedSections.worldCharacters ? <UpOutline /> : <DownOutline />
            }
          </div>
        </div> */}
        <Picker
          columns={genderColumns}
          visible={genderVisible}
          onClose={() => {
            setGenderVisible(false)
          }}
          value={form.getFieldValue('gender')}
          onConfirm={v => {
            form.setFieldsValue({
              gender: v[0]
            })
            setGenderVisible(false)
          }}
        />
        <Picker
          columns={raceColumns}
          visible={raceVisible}
          onClose={() => {
            setRaceVisible(false)
          }}
          value={form.getFieldValue('race')}
          onConfirm={v => {
            form.setFieldsValue({
              race: v[0]
            })
            setRaceVisible(false)
          }}
        />
        <Picker
          columns={world_categoryColumns}
          visible={worldTypeVisible}
          onClose={() => {
            setWorldTypeVisible(false)
          }}
          value={form.getFieldValue('world_type')}
          onConfirm={v => {
            form.setFieldsValue({
              world_type: v[0]
            })
            setWorldTypeVisible(false)
          }}
        />
        <Picker
          columns={era_backgroundColumns}
          visible={eraBackgroundVisible}
          onClose={() => {
            setEraBackgroundVisible(false)
          }}
          value={form.getFieldValue('era_background')}
          onConfirm={v => {
            form.setFieldsValue({
              era_background: v[0]
            })
            setEraBackgroundVisible(false)
          }}
        />
      </Form>

      {/* <CreationMethod show={!id} onSelect={handleSelMethod} /> */}
    </div>
  );
};

export default WorldCreationForm;